package com.kinon.tyjaccount.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.adapter.CaidanAdapter;
import com.kinon.tyjaccount.entity.CaidanEntity;
import com.kinon.tyjaccount.entity.ItemBean;
import com.kinon.tyjaccount.entity.KVP;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.MyShowDialog;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.SendShopList;
import com.kinon.tyjaccount.tools.ToastUtil;
import com.kinon.tyjaccount.tools.Utility;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import sunmi.ds.DSKernel;

/**二维码取餐详情*/

public class DingdandetialerweimaActivity extends Activity {

	private CaidanAdapter caidanAdapter;
	private TextView tv_name;
	private TextView tv_bianhao;
	private TextView tv_time;
	private TextView tv_amount;
	private TextView tv_heji;
	private TextView tv_fanhui;
	private Button btn_queren;
	/**菜单列表*/
	private ListView lv;

	/**获得数据*/
	ArrayList<CaidanEntity> infolist;
	HttpTools httptools=null;
	int shuliang;
	String id;
	//副屏显示的菜品列表
	List<ItemBean> items ;
	//副屏的取餐编号和共计
	List<KVP> sm ;
	DSKernel mDSKernel;// SDK核心类

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dingdandetial);
		initRes();
	}

	private void initRes() {
		lv=(ListView)findViewById(R.id.lv_caipin);
		tv_name=(TextView)findViewById(R.id.tv_name);
		tv_bianhao=(TextView)findViewById(R.id.tv_bianhao);
		tv_time=(TextView)findViewById(R.id.tv_time);
		tv_amount=(TextView)findViewById(R.id.tv_amount);
		tv_heji=(TextView)findViewById(R.id.tv_heji);
		tv_fanhui=(TextView)findViewById(R.id.tv_fanhui);
		tv_fanhui.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		btn_queren=(Button)findViewById(R.id.btn_queren);
		btn_queren.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Queren();
			}
		});
		mDSKernel = DSKernel.newInstance();//副屏初始化
		Caidan();
	}

	/**获取订单详情*/
	private void Caidan() {
		if(NetWorkUtil.isNetwork(getApplicationContext())==false)
		{
			ToastUtil toastUtil=new ToastUtil();
			toastUtil.Short(getApplicationContext(),"  "+"当前网络不可用")
					.setToastBackground(Color.WHITE,0).show();
			return;
		}
		infolist=new ArrayList<CaidanEntity>();
		items = new ArrayList<>();
		sm = new ArrayList<>();
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		String token = sp.getString("data", "");
		String orderid = getIntent().getStringExtra("orderid");
//		Toast.makeText(getApplicationContext(), orderid, Toast.LENGTH_SHORT).show();
		Log.i("info","dayno---" +orderid.substring(0, 16));
		Log.i("info","data---" +token);
		if (httptools == null) {
			httptools = new HttpTools(getApplicationContext());
		}
		httptools.getDetail(token, orderid, "","",new JsonCaidan());

	}

	public class JsonCaidan extends JsonHttpResponseHandler {
		@Override
		public void onStart() {
			MyShowDialog.showLoadingDialog(DingdandetialerweimaActivity.this, "请稍后....");
			super.onStart();
		}
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {

			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			MyShowDialog.closeLoadingDialog();
			try {
				Log.i("zq",response.toString());
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if (code == true) {
					Log.i("zq", "订单详情---"+response.toString());
					JSONObject object = response.getJSONObject("data");
					String username = object.getString("name");
					id = object.getString("id");
					//					String order_time = object.getString("order_time");
					String take_time = object.getString("take_time");
					String book_time = object.getString("book_time");
					String dayno = object.getString("dayno");
					//					String paymodeid = object.getString("paymodeid");
					String total = object.getString("total");
					//					String fee = object.getString("fee");
					//					String recmode = object.getString("recmode");
					String orderno = object.getString("orderno");
					String state = object.getString("state");
					//					String refund = object.getString("refund");
					//					String more = object.getString("more");
					//					String off = object.getString("off");

					//添加副屏末尾信息
					sm.add(new KVP("取餐编号",dayno));
					sm.add(new KVP("共计",total));
					JSONArray array = object.getJSONArray("details");
					for (int j = 0;j < array.length(); j++) {					
						JSONObject details = array.getJSONObject(j);
						String caipinid = details.getString("id");
						String name = details.getString("name");
						String amount = details.getString("amount");
						String price = details.getString("price");
						String totalprice = details.getString("total");
						shuliang+=Integer.parseInt(amount);
						//						double jine =+ Integer.parseInt(amount)*Double.parseDouble(price);
						//						String sname = details.getString("sname");
						//添加副屏列表信息
						items.add(new ItemBean(caipinid,name,price,amount,totalprice));
						infolist.add(new CaidanEntity(caipinid, amount, name, price, 1));							
					}
					if (state.equals("1")) {
						btn_queren.setText("确认收货");
					}else if (state.equals("2")) {
						btn_queren.setText("已完成");
					}
					tv_name.setText(username);
					tv_amount.setText(""+shuliang);
					tv_heji.setText(total);
					tv_bianhao.setText(dayno);
					tv_time.setText(book_time);
					//					tv_heji.setText(total);
					caidanAdapter = new CaidanAdapter(getApplicationContext(), infolist);
					lv.setAdapter(caidanAdapter);
					lv.setDivider(null);
					Utility.setListViewHeightBasedOnChildren(lv);
					//向副屏发送数据
					SendShopList sendShopList =new SendShopList(getApplicationContext(),mDSKernel,items,sm);
					sendShopList.getInstance(getApplicationContext(),mDSKernel,items,sm);
					sendShopList.send(false,"");
				}else {
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		@Override
		public void onFailure(Throwable e, JSONObject errorResponse) {
			super.onFailure(e, errorResponse);
			MyShowDialog.closeLoadingDialog();
			Toast.makeText(DingdandetialerweimaActivity.this,
					"网络请求失败", Toast.LENGTH_SHORT).show();
		}
	}

	/**确认收货操作*/
	private void Queren() {
		//	infolist=new ArrayList<CaidanEntity>();
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		String token = sp.getString("data", "");
//		String orderid = getIntent().getStringExtra("orderid");
		//	Log.i("info","orderid---" +orderid);
		//	Log.i("info","data---" +token);
		if (httptools == null) {
			httptools = new HttpTools(getApplicationContext());
		}
		httptools.updateOrder(token, id, "2",new JsonQueren());

	}

	public class JsonQueren extends JsonHttpResponseHandler {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			try {
				Log.i("zq",response.toString());
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if (code == true) {
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(DingdandetialerweimaActivity.this,WancanpayresultActivity.class);
					startActivity(intent);
					finish();
				}else {
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		@Override
		public void onFailure(Throwable e, JSONObject errorResponse) {
			super.onFailure(e, errorResponse);
			Toast.makeText(DingdandetialerweimaActivity.this,
					"网络请求失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override    
    public boolean onKeyDown(int keyCode, KeyEvent event) {    
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {    
//             System.out.println("按下了back键   onKeyDown()");     
//        	Intent intent = new Intent();
//        	intent.setClass(DingdandetialerweimaActivity.this, MainActivity.class);
//        	intent.putExtra("code", "1");
//        	startActivity(intent);
        	finish();
        	
             return false;    
        }else {    
            return super.onKeyDown(keyCode, event);    
        }    
            
    }    
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
	       super.onWindowFocusChanged(hasFocus);
	       if (hasFocus) {
	            View decorView = getWindow().getDecorView();
	                 decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
	                  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
	                  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
	                  |View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 
	                  |View.SYSTEM_UI_FLAG_FULLSCREEN);
	               }
	}

}
